package com.system.util;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.common.util.SpringUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName MapperUtils
 * @Description TODO
 * @Author 无名小卒
 * @Date 2023/9/2 22:35
 * @Version 1.0
 */
@Component
@ConditionalOnBean(SpringUtil.class)
public class MapperUtils implements InitializingBean {
    @Autowired
    private SpringUtil springUtil;
    private final Map<String, BaseMapper> mapperyConcurrentHashMap = new ConcurrentHashMap<>();


    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, BaseMapper> statementHandles = springUtil.getBeansOfType(BaseMapper.class);
        for (String key:statementHandles.keySet()) {
            mapperyConcurrentHashMap.put(key,statementHandles.get(key));
        }
    }

    public  BaseMapper getMapper(String mapper){
        BaseMapper baseMapper=null;
        for (String key:mapperyConcurrentHashMap.keySet()) {
            if(key.equalsIgnoreCase(mapper)){
                baseMapper=mapperyConcurrentHashMap.get(key);
                break;
            }
        }
        return  baseMapper;
    }

    public  Class getEntiyClass(String mapper){
        BaseMapper baseMapper=null;
        for (String key:mapperyConcurrentHashMap.keySet()) {
            if(key.equalsIgnoreCase(mapper)){
                baseMapper=mapperyConcurrentHashMap.get(key);
                break;
            }
        }
        Class typeName = (Class) ((ParameterizedTypeImpl) ((Class) baseMapper.getClass()
                .getGenericInterfaces()[0]).getGenericInterfaces()[0])
                .getActualTypeArguments()[0];
       return typeName;
    }
}
